package com.bobbygu.bobbyapp.view.showview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.Random;

/**
 * 简单的雪
 *
 * @author BobbyGu
 * @date 2017/12/28
 */

public class SimpleSnowView extends View {
    private static final Random RANDOM = new Random();
    private static final int SNOW_NUM = 150;
    private Snow[] snows = new Snow[SNOW_NUM];
    private Paint snowPaint = new Paint();

    public SimpleSnowView(Context context) {
        super(context);
    }

    public SimpleSnowView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SimpleSnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        snowPaint.setColor(Paint.ANTI_ALIAS_FLAG);
        snowPaint.setColor(Color.WHITE);
        snowPaint.setStyle(Paint.Style.FILL);
        for (int i = 0; i < SNOW_NUM; i++) {
            snows[i] = new Snow();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != oldw || h != oldh) {
            init();
        }
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        Snow snow;
        for (int i = 0; i < SNOW_NUM; i++) {
            snow = snows[i];
            snow.x += snows[i].vx;
            snow.y += snows[i].vy;
            if (snow.x < 0) {
                snow.x = getWidth();
            }
            if (snow.x > getWidth()) {
                snow.x = 0;
            }
            if (snow.y > getHeight()) {
                snow.y = 0;
            }
            canvas.drawCircle(snow.x, snow.y, snow.size, snowPaint);
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        invalidate();
    }

    class Snow {
        int x;
        int y;
        float vx;
        float vy;
        float size;
        int color;

        Snow() {
            x = RANDOM.nextInt(getWidth());
            y = RANDOM.nextInt(getHeight());
            vx = RANDOM.nextFloat() - 2;
            vy = RANDOM.nextFloat() + 2;
            size = RANDOM.nextFloat() * 10 + 5;
            color = Color.WHITE;
        }
    }
}
